package net.y2t72.microblog.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.log4j.Logger;

/**
 * 数据库连接管理类
 * @author Administrator
 *
 */
public final class ConnectionManager {
	/*
	 * Logger对象
	 */
	private static Logger logger = Logger.getLogger(ConnectionManager.class);

	/**
	 * 私有自身对象
	 */
	private static ConnectionManager instance = null;
	

	/**
	 * 单例模式 获取对象实例
	 * 
	 * @return ConnectionManager对象
	 */
	public static ConnectionManager getInstance() {
		if (instance == null) {
			synchronized (ConnectionManager.class) {
				if (instance == null) {
					instance = new ConnectionManager();
				}
			}
		}
		return instance;
	}

	/**
	 * 注册驱动
	 */
	static {
		if(InitialProperties.getInstance().getProperty("type")!= null){
			try {
				Class.forName(InitialProperties.getInstance().getProperty("driverClassName"));
			} catch (ClassNotFoundException e) {
				logger.error("未找到驱动类,异常信息:" + e.getStackTrace(),e.getCause());
			}
		}
	}

	/**
	 * 获取连接对象
	 * 
	 * @return Connection对象
	 * @throws Exception 
	 */
	public Connection getConnection() throws Exception {
		Connection conn = null;
		if(InitialProperties.getInstance().getProperty("type") != null){
			conn = DriverManager.getConnection(InitialProperties.getInstance().getProperty("url"),
					InitialProperties.getInstance().getProperty("username"), InitialProperties.getInstance().getProperty("password"));
		}else{
			DataSource ds = BasicDataSourceFactory.createDataSource(InitialProperties.getInstance());
			conn = ds.getConnection();
		}
		return conn;
	}
}
